
using System;
using System.Collections.Generic;
using System.IO;
using Qdb.Tests.Util;

namespace Qdb.Tests.Common.Migration
{
	public class QdbLibrarian
	{
		private const string MinimumVersionToTest = "6.0";
		private readonly QdbLibraryEnvironmentProvider _provider;

		public QdbLibrarian(QdbLibraryEnvironmentProvider provider)
		{
			_provider = provider;
		}

		public QdbLibrary[] Libraries()
		{
            List <QdbLibrary> libraries = new List<QdbLibrary>();
			foreach (string path in Directory.GetDirectories(LibraryPath()))
			{
				// comment out the next line to run against legacy versions
				if (!IsVersionOrGreater(path, MinimumVersionToTest))
					continue;

				string qdbLib = FindLibraryFile(path);
				if (null == qdbLib) continue;
				libraries.Add(ForFile(qdbLib));
			}
			return libraries.ToArray();
		}

		private static bool IsVersionOrGreater(string path, string minimumVersion)
		{
#if !CF
			string folderName = Path.GetFileName(path);
			if (folderName == ".svn") return false;

			Version candidate = new Version(folderName);
			Version minimum = new Version(minimumVersion);

			if (candidate.Major > minimum.Major)
				return true;

			return candidate.Major == minimum.Major && candidate.Minor >= minimum.Minor;
#endif
			return false;
		}

		public static string LibraryPath()
		{
			return WorkspaceServices.WorkspacePath("qdb.archives/net-2.0");
		}

		public QdbLibrary ForVersion(string version)
		{
			return ForFile(FindLibraryFile(Path.Combine(LibraryPath(), version)));
		}

		public QdbLibrary ForFile(string qdbLib)
		{
			return new QdbLibrary(qdbLib, EnvironmentFor(qdbLib));
		}

		private static string FindLibraryFile(string directory)
		{
			string[] found = Directory.GetFiles(directory, "*.dll");
			return found.Length == 1 ? found[0] : null;
		}

		private QdbLibraryEnvironment EnvironmentFor(string qdbLib)
		{
			return _provider.EnvironmentFor(qdbLib);
		}

    }

}